<?php

/**
 * 73YC 商品分类
 * ============================================================================
 * * 版权所有 20013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}

/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */



/* 获得请求的分类 ID */
if (isset($_REQUEST['id']))
{
    $cat_id = intval($_REQUEST['id']);
}
elseif (isset($_REQUEST['category']))
{
    $cat_id = intval($_REQUEST['category']);
}
else
{
    /* 如果分类ID为0，则返回首页 */
    ecs_header("Location: ./\n");
    exit;
}

if($cat_id==101){
    ecs_header("Location: ./\n");
    exit();
}

assign_template();

/* 初始化分页信息 */
$page = isset($_REQUEST['page'])   && intval($_REQUEST['page'])  > 0 ? intval($_REQUEST['page'])  : 1;
$size = 34;
//页面排序类型
$sort  = (isset($_REQUEST['sort'])  && in_array(trim(strtolower($_REQUEST['sort'])), array('buy_sum', 'sort_orders', 'click_count', 'shop_price', 'last_update'))) ? trim($_REQUEST['sort'])  : "sort_orders";
//页面排序方式
$order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC'))) ? trim($_REQUEST['order']) : $default_sort_order_method;

/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */

/* 页面的缓存ID */
$cache_id = sprintf('%X', crc32($cat_id . '-'  . $page .'-' . $order  .'-' . $sort  . '-' . $size . '-' . $_SESSION['area_id'] . '-' . $_CFG['lang'] .'-' . $filter_attr_str));

if (!$smarty->is_cached('category.dwt', $cache_id))
{   
    
    (!$cat_id || $cat_id==0) && $cat_id = 298;
    
    /* 如果页面没有被缓存则重新获取页面的内容 */
    $children = get_children($cat_id);
    $cat = get_cat_info($cat_id);
   
    /* 从缓存中读取3级分类 */
    $cat_all = get_3layer_cache_cat($cat_id);
    
    /* 从数据库中读取3级分类 */ 
    /* $cat_all = get_3layer_cat($cat);*/
    
    $smarty->assign('cat_layer1',$cat_all[1]);
    $smarty->assign('cat_layer2',$cat_all[2]);
    
    if (!empty($cat))
    {
        $smarty->assign('keywords',    htmlspecialchars($cat['keywords']));
        $smarty->assign('description', htmlspecialchars($cat['cat_desc']));
        $smarty->assign('cat_style',   htmlspecialchars($cat['style']));
    }
    else
    {
        /* 如果分类不存在则读取 */
        ecs_header("Location: ./\n");
        exit;
    }
    $position = assign_ur_here();
    $smarty->assign('page_title',       $position['title']);    // 页面标题
    $smarty->assign('cat_id',           $cat_id);
    //统计页面数量进行分页
    $count = get_cagtegory_goods_count($children);
    $smarty->assign('script_name', 'category');
    assign_pager('category', $cat_id, $count, $size, $sort, $order, $page, '', $brand, $price_min, $price_max, $display, $filter_attr_str); // 分页
    assign_dynamic('category'); // 动态内容
    $goodslist = category_get_goods($children,$size, $page, $sort, $order);  
    $smarty->assign('goods_list',       $goodslist);


    $goods_random = category_get_goods_random(); //获取随机查询的商品信息
    $goods_hot = category_get_goods_hot(); //获取热销产品

    $smarty->assign('goods_hot',       $goods_hot);
    $smarty->assign('goods_random',    $goods_random);
}

/* 获取产品列表底部广告 */
$ad_1=get_ad(12);//产品列表底部广告
$smarty->assign('ad_1', $ad_1);

/* 获取产品品牌商标LOGO */
$sql = "SELECT * FROM " . $GLOBALS['ecs']->table('brand') . " WHERE sort_order between 0 and 24 ORDER BY RAND() LIMIT 24 ";
$brand_list = $db->getAll($sql);

$smarty->assign('is_buy',       is_buy());
$smarty->assign('brand_list',      $brand_list);
$smarty->assign('hot_goods',       get_recommend_goods('hot'));

$smarty->display('category.dwt', $cache_id);



/*------------------------------------------------------ */
//-- PRIVATE FUNCTION
/*------------------------------------------------------ */


/**
 * 从缓存文件中获得三级分类，基本思路是根据层级来判断
 *
 * @param   array $cat_info
 *
 * @return  array
 */
function get_3layer_cache_cat($cat_id){
    
    $cat_data = read_static_cache('cat_option_static');
    $cat_info = $cat_data[$cat_id];
    /* $sort_order 用于给二维数据排序，二维数据中的 sort_order 值排序 */
    $cat_layer1 = $cat_layer2 = $sort_order = array();
    
    foreach ($cat_data as $k => $v)  {
        $cat_data[$k]['url'] = build_uri('category', array('cid' => $v['cat_id']), $v['cat_name']);
        if(!$v['is_show']) unset($cat_data[$k]);
    }
    
    if($cat_info['level'] == 1){
        foreach($cat_data as $k => $v){
            if($v['parent_id'] == $cat_info['parent_id']) 
            {    
                $cat_layer1[$k] = $v;
                $sort_order[$k] = $v['sort_order'];
            }
            if($v['parent_id'] == $cat_info['cat_id'])
            {
                $cat_layer2[$k] = $v; 
                foreach ($cat_data as $key => $value) if($value['parent_id'] == $cat_layer2[$k]['cat_id']) $cat_layer2[$k]['sub_cat'][$key] = $value;
            }
        }
    }
    
    if($cat_info['level'] == 2){
        foreach($cat_data as $k => $v){
            if($v['parent_id'] == $cat_data[$cat_info['parent_id']]['parent_id']) 
            {
                $cat_layer1[$k] = $v;
                $sort_order[$k] = $v['sort_order'];
                if( $cat_info['parent_id'] == $v['cat_id']) $cat_layer1[$k]['current_layer'] = 1;
            }
            if($v['parent_id'] == $cat_info['parent_id']) 
            {
                $cat_layer2[$k] = $v;
                foreach ($cat_data as $key => $value) if($value['parent_id'] == $cat_layer2[$k]['cat_id']) $cat_layer2[$k]['sub_cat'][$key] = $value;
            }
        }
    }
    
    if($cat_info['level'] == 3){
        foreach($cat_data as $k => $v){
            if($v['parent_id'] == $cat_data[$cat_data[$cat_info['parent_id']]['parent_id']]['parent_id'])  
            {
                $cat_layer1[$k] = $v;
                $sort_order[$k] = $v['sort_order'];
                if( $cat_data[$cat_info['parent_id']]['parent_id'] == $v['cat_id']) $cat_layer1[$k]['current_layer'] = 1;
            }
            if($v['parent_id'] == $cat_data[$cat_info['parent_id']]['parent_id']) 
            {
                $cat_layer2[$k] = $v;
                foreach ($cat_data as $key => $value) if($value['parent_id'] == $cat_layer2[$k]['cat_id']) $cat_layer2[$k]['sub_cat'][$key] = $value;
            }
        } 
    }    
    
    /* 二维数据 $cat_layer1 排序，按二维数据中第二维的数组中 key 为 sort_order 的值降序 */
    array_multisort( $sort_order,SORT_DESC ,$cat_layer1);
    
    return array(1=>$cat_layer1,2=>$cat_layer2);
}

/**
 * 获得三级分类，基本思路是根据层级来判断
 *
 * @param   array $cat_info
 *
 * @return  array
 */
function get_3layer_cat($cat_info){
    /*  如果当前是一级分类，取得当前分类及当前分类的下级分类（二级分类）、下下级分类（三级分类） */
    if($cat_info['layer'] == 1){
        /* 一级分类，即读取与当前分类同级的所有一级分类 */
        $cat_layer1 = $GLOBALS['db']->getAll("SELECT `cat_id`, `cat_name`, `keywords`, `cat_desc`, `style`, `grade`, `filter_attr`, `parent_id`, `layer` FROM  {$GLOBALS['ecs']->table('category')} WHERE `parent_id` = {$cat_info['parent_id']} ORDER BY `sort_order` DESC");
        /* 二级分类 包含 三级分类 */
        $cat_layer2 = $GLOBALS['db']->getAll("SELECT `cat_id`, `cat_name`, `keywords`, `cat_desc`, `style`, `grade`, `filter_attr`, `parent_id`, `layer` FROM  {$GLOBALS['ecs']->table('category')} WHERE `parent_id` = {$cat_info['cat_id']} ORDER BY `sort_order` ASC");
        foreach ($cat_layer2 as $k => $v){
            $cat_layer2[$k]['sub_cat'] = get_child_tree($v['cat_id']);
        }
    } 
    /* 如果当前是二级分类，取得当前分类上级分类（一级分类）、当前分类的下级分类（三级分类） */
    if($cat_info['layer'] == 2){
        /* 二级分类 */
        $cat_layer2 = $GLOBALS['db']->getAll("SELECT `cat_id`, `cat_name`, `keywords`, `cat_desc`, `style`, `grade`, `filter_attr`, `parent_id`, `layer` FROM  {$GLOBALS['ecs']->table('category')} WHERE `parent_id` = {$cat_info['parent_id']} ORDER BY `sort_order` ASC");
        /* 一级分类，即读取与当前父分类同级的所有一级分类 */
        $p_parent_cat_id = $GLOBALS['db']->getOne("SELECT `parent_id` FROM  {$GLOBALS['ecs']->table('category')} WHERE `cat_id` = {$cat_info['parent_id']} LIMIT 1");
        $cat_layer1 = $GLOBALS['db']->getAll("SELECT `cat_id`, `cat_name`, `keywords`, `cat_desc`, `style`, `grade`, `filter_attr`, `parent_id`, `layer` FROM  {$GLOBALS['ecs']->table('category')} WHERE `parent_id` = {$p_parent_cat_id} ORDER BY `sort_order` DESC");
        foreach ($cat_layer2 as $k => $v){
            $cat_layer2[$k]['sub_cat'] = get_child_tree($v['cat_id']);
        }
        /* 是否是当前分类的一级分类，用于一级分类的选中状态 */
        foreach($cat_layer1 as $k => $v){
            if($cat_info['parent_id'] == $v['cat_id']){
                $cat_layer1[$k]['current_layer'] = 1;
            }else{
                $cat_layer1[$k]['current_layer'] = 0;
            }
        } 
    }
    /* 如果当前是第三级分类，取得当前分类及当前分类的上级分类（二级分类）、上上级分类（一级分类） */
    if($cat_info['layer'] == 3){
        /* 二级分类，与当前父级同级的分类 */
        $p_parent_cat_id = $GLOBALS['db']->getOne("SELECT `parent_id` FROM  {$GLOBALS['ecs']->table('category')} WHERE `cat_id` = {$cat_info['parent_id']} LIMIT 1");
        $cat_layer2 =  $GLOBALS['db']->getAll("SELECT `cat_id`, `cat_name`, `keywords`, `cat_desc`, `style`, `grade`, `filter_attr`, `parent_id`, `layer` FROM  {$GLOBALS['ecs']->table('category')} WHERE `parent_id` = $p_parent_cat_id ORDER BY `sort_order` ASC");
        /* 一级分类 与当前父级父级同级的分类 */
        $p_p_parent_cat_id = $GLOBALS['db']->getOne("SELECT `parent_id` FROM  {$GLOBALS['ecs']->table('category')} WHERE `cat_id` = {$p_parent_cat_id} LIMIT 1");
        $cat_layer1 =  $GLOBALS['db']->getAll("SELECT `cat_id`, `cat_name`, `keywords`, `cat_desc`, `style`, `grade`, `filter_attr`, `parent_id`, `layer` FROM  {$GLOBALS['ecs']->table('category')} WHERE `parent_id` = $p_p_parent_cat_id ORDER BY `sort_order` DESC");
        foreach ($cat_layer2 as $k => $v){
            $cat_layer2[$k]['sub_cat'] = get_child_tree($v['cat_id']);
            if($cat_info['parent_id']==$v['cat_id']){
                $cat_layer2[$k]['current_layer'] = 1;
            }else{
                $cat_layer2[$k]['current_layer'] = 0;
            }
        }
        /* 是否是当前分类的一级分类，用于一级分类的选中状态 */
        foreach($cat_layer1 as $k => $v){
            if($p_parent_cat_id==$v['cat_id']){
                $cat_layer1[$k]['current_layer'] = 1;
            }else{
                $cat_layer1[$k]['current_layer'] = 0;
            }
        }
    }
    foreach ($cat_layer1 as $k => $v){
        $cat_layer1[$k]['url']  = build_uri('category', array('cid' => $v['cat_id']), $v['cat_name']);
    }
    foreach ($cat_layer2 as $k => $v){
        $cat_layer2[$k]['url']  = build_uri('category', array('cid' => $v['cat_id']), $v['cat_name']);
    }
    return array(1=>$cat_layer1,2=>$cat_layer2);
}


/**
 * 获得分类的信息
 *
 * @param   integer $cat_id
 *
 * @return  void
 */
function get_cat_info($cat_id)
{
    return $GLOBALS['db']->getRow('SELECT cat_id, cat_name, keywords, cat_desc, style, grade, filter_attr, parent_id, layer FROM ' . $GLOBALS['ecs']->table('category') .
        " WHERE cat_id = '$cat_id'");
}

/**
 * 获得分类下的商品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function category_get_goods($children, $size, $page, $sort, $order)
{
    $display = $GLOBALS['display'];
    $where = "g.warn_number = 1 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND ".
            "g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')';
    if($sort == 'shop_price'){
        $sort = '(g.shop_price)';
    }
    /* 获得商品列表 */
    $sql = 'SELECT g.goods_id,g.shopall_note, g.goods_name, g.shop_price, g.preferential_price2, g.preferential_price5, g.goods_name_style, g.click_count, g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_thumb , g.goods_img, g.goods_type, g.is_new, g.is_taodan, ' .
                "(select sum(goods_number) from " . $GLOBALS['ecs']->table('order_goods') . " WHERE goods_id = g.goods_id ) AS buy_sum, ".
                "(select sum(goods_number) from " . $GLOBALS['ecs']->table('goods_stock') . " WHERE goods_id = g.goods_id AND area_id = $_SESSION[area_id] ) AS goods_number ". 
                'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . 
                " WHERE $where ORDER BY $sort $order";

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['promote_price'] > 0)
        {
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }
        else
        {
            $promote_price = 0;
        }

        $arr[$row['goods_id']]['goods_id']         = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']       = $row['goods_name'];

        if($row['shopall_note']){
            $arr[$row['goods_id']]['goods_name']             = $row['shopall_note'];
        }

        $arr[$row['goods_id']]['click_count']      = $row['click_count'];
        $arr[$row['goods_id']]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']);
        if($row['market_price'] > 0){//存在市场价
            $arr[$row['goods_id']]['market_price'] = price_format(sprintf('%.1f',$row['market_price']));
        }else{//当不存在市场价时的市场价
            $arr[$row['goods_id']]['market_price'] = price_format(sprintf('%.1f',($row['shop_price'])*1.2));
        }
        $arr[$row['goods_id']]['shop_price']       = price_format($row['shop_price']);
        $arr[$row['goods_id']]['preferential_price2']  = ($row['preferential_price2'] > 0) ? price_format($row['preferential_price2']) : ''; //第二梯度价格
        $arr[$row['goods_id']]['preferential_price5']  = ($row['preferential_price5'] > 0) ? price_format($row['preferential_price5']) : ''; //第五梯度价格
        $arr[$row['goods_id']]['type']             = $row['goods_type'];
        $arr[$row['goods_id']]['promote_price']    = ($promote_price > 0) ? price_format($promote_price) : '';
        $arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $arr[$row['goods_id']]['buy_sum']          = intval($row['buy_sum']);
        $arr[$row['goods_id']]['thumb_list']       = get_thumb($row['goods_id']);
        $arr[$row['goods_id']]['goods_number']     = $row['goods_number'];
        $arr[$row['goods_id']]['shopall_note']     = $row['shopall_note'];
        $arr[$row['goods_id']]['is_new']           = $row['is_new'];
        $arr[$row['goods_id']]['is_taodan']        = $row['is_taodan'];
    }
    
    return $arr;
    
}

/**
 * 获得分类下的商品总数
 *
 * @access  public
 * @param   string     $cat_id
 * @return  integer
 */
function get_cagtegory_goods_count($children, $brand = 0, $min = 0, $max = 0, $ext='')
{
    $where  = "g.warn_number = 1 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')';

    if ($brand > 0)
    {
        $where .=  " AND g.brand_id = $brand ";
    }

    /* 返回商品总数 */
    return $GLOBALS['db']->getOne('SELECT COUNT(*) FROM ' . $GLOBALS['ecs']->table('goods') . " AS g WHERE $where $ext");
}

/**
 * 获得广告位
 *
 * @access  private
 * @return  array
 */
function get_ad($position_id = 0){
        if(!$position_id) return false;
        $position_id = intval($position_id);
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('ad') . " WHERE position_id = '$position_id' ORDER BY ad_name ASC ";
        return $GLOBALS['db']->getAll($sql);
    }


/**
 * 获得热销的商品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function category_get_goods_hot()
{         
    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.promote_price, g.goods_thumb , g.goods_img, g.is_hot, ' . 
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " . 
        ' FROM '. $GLOBALS['ecs']->table('goods') . 'AS g ' . 
        " WHERE g.is_hot = 1 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ORDER BY RAND() LIMIT 15";    
    $res = $GLOBALS['db']->query($sql);
    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['goods_id']]['goods_id']         = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']       = $row['goods_name'];
        $arr[$row['goods_id']]['shop_price']       = price_format($row['shop_price']);
        $arr[$row['goods_id']]['promote_price']    = ($promote_price > 0) ? price_format($promote_price) : '';
        $arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $arr[$row['goods_id']]['is_hot']           = $row['is_hot'];
        $arr[$row['goods_id']]['counts']           = $row['counts'];
    }
    return $arr;
}

/**
 * 获得随机查询的商品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function category_get_goods_random()
{
    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.promote_price, g.goods_thumb , g.goods_img, ' . 
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " . 
        ' FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .  
        " WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ORDER BY RAND() LIMIT 15";
    $res = $GLOBALS['db']->query($sql);
    
    $arr = array();
    $i=0;
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$i]['goods_id']               = $row['goods_id'];
        $arr[$i]['goods_name']       = $row['goods_name'];
        $arr[$i]['shop_price']       = price_format($row['shop_price']);
        $arr[$i]['promote_price']    = ($promote_price > 0) ? price_format($promote_price) : '';
        $arr[$i]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$i]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$i]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $arr[$i++]['counts']         = $row['counts'];
    }
    return $arr;
}

?>